package cap.action;

import cap.bean.*;
import cap.dao.*;
import cap.dao.impl.*;
import cap.util.PageControl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private AdminDao adminDao;
    private UserDao userDao;
    private ProfileDao profileDao;
    private ArticleDao articleDao;
    private SysCategoryDao sysCategoryDao;
    private CounterDao counterDao;
    private CommentDao commentDao;
    public AdminServlet() {
        adminDao=new AdminDaoImpl();
        userDao=new UserDaoImpl();
        profileDao=new ProfileDaoImpl();
        articleDao=new ArticleDaoImpl();
        sysCategoryDao=new SysCategoryDaoImpl();
        counterDao=new CounterDaoImpl();
        commentDao=new CommentDaoImpl();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String method=request.getParameter("method");
        if(method.equals("logout")){//登出
            HttpSession session = request.getSession(false);//防止创建Session
            if (null != session) {
                session.removeAttribute("admin");
            }
            request.getSession().setAttribute("logoutMsg", "退出成功！");
            response.sendRedirect("login.jsp");
        }else if(method.equals("index")){//管理员页面
            List<Article> artList = articleDao.getAllArtical(); //获取所有文章
            List<Comment> cmtList = commentDao.getAll(); //获取所有评论
            List<User> uList = userDao.getAllUser(); //获取所有用户
            Counter cnt = counterDao.getCounter();//获取网站来访数
            request.setAttribute("artList", artList);
            request.setAttribute("cmtList", cmtList);
            request.setAttribute("uList", uList);
            request.setAttribute("cnt", cnt);
            request.getRequestDispatcher("admin/admin.jsp").forward(request, response);
        }
        else if(method.equals("useradmin")){//用户管理
            String curPageStr = request.getParameter("curPage");
            int curPage=1;
            if(curPageStr!=null){
                curPage=Integer.parseInt(curPageStr);
            }//分页
            PageControl pc = new PageControl(curPage, userDao.getAllUser().size());//获取当前页码的用户信息
            List<User> uList=userDao.getUserByPage(pc.getCurPage(), pc.getPageSize());
            pc.setList(userDao.getAllUser());
            request.setAttribute("curPage", pc.getCurPage());
            request.setAttribute("totalPages", pc.getTotalPages());
            request.setAttribute("uList", pc.getList());
            request.getRequestDispatcher("admin/UserAdmin.jsp").forward(request, response);
        }else if(method.equals("userprofile")){//用户详细信息
            int userId = Integer.parseInt(request.getParameter("uId"));
            Profile pf = profileDao.getByuserId(userId);//用户详细信息
            request.setAttribute("pf", pf);
            request.getRequestDispatcher("admin/UserProfile.jsp").forward(request, response);
        }else if(method.equals("deleteuser")){//禁用账号
            int uId = Integer.parseInt(request.getParameter("uId"));
            int res = userDao.deleteUser(uId);
            if (res > 0) {	//删除成功
                request.getSession().setAttribute("succDeleMsg", "禁用账户成功！");
            } else {     //删除失败
                request.getSession().setAttribute("errorDeleMsg", "禁用账户失败！");
            }
            response.sendRedirect("admin?method=useradmin");
        }else if(method.equals("activeuser")){//激活账号
            int uId = Integer.parseInt(request.getParameter("uId"));
            int res = userDao.activeUser(uId);
            if (res > 0) {	//激活成功
                request.getSession().setAttribute("succActMsg", "激活账户成功！");
            } else {     //激活失败
                request.getSession().setAttribute("errorActMsg", "激活账户失败！");
            }
            response.sendRedirect("admin?method=useradmin");
        }else if(method.equals("SysArticalAdmin")){//文章管理
            String curPageStr = request.getParameter("curPage");
            int curPage=1;
            if(curPageStr!=null){
                curPage=Integer.parseInt(curPageStr);
            }
            int count=articleDao.getAllArtical().size();
            PageControl pc = new PageControl(curPage, count);//获取当前页码文章信息
            List<Article> artList= articleDao.getArticleByPage(curPage, articleDao.getAllArtical().size());
            pc.setList(articleDao.getAllArtical());
            System.out.println(articleDao.getAllArtical());
            request.setAttribute("curPage", pc.getCurPage());
            request.setAttribute("totalPages", pc.getTotalPages());
            request.setAttribute("artList", artList);
            request.getRequestDispatcher("admin/SysArticleAdmin.jsp").forward(request, response);
        }else if(method.equals("DeleteSysArtical")){//删除文章
            int artId = Integer.parseInt(request.getParameter("artId"));
            int res = articleDao.deleteArtical(artId);
            if (res > 0) {	//删除成功
                request.getSession().setAttribute("deleSuccMsg", "删除成功！");
            } else {
                request.getSession().setAttribute("deleErrorMsg", "删除失败！");
            }
            response.sendRedirect("admin?method=SysArticalAdmin");
        }else if(method.equals("SysCategoryAdmin")){//分类管理
            String curPage=request.getParameter("curPage");
            int curPageStr =1;
            if(null!=curPage) {
                curPageStr=Integer.parseInt(curPage);
                PageControl pc = new PageControl(curPageStr, sysCategoryDao.count());
                List<SysCategory> sysCategories=sysCategoryDao.getSysCategoryByPage(curPageStr,pc.getPageSize());
                pc.setList(sysCategoryDao.getAllSysCategory());//获取当前页码系统分类
                request.setAttribute("scgList", pc.getList());
                request.setAttribute("curPage", pc.getCurPage());
                request.setAttribute("totalPages", pc.getTotalPages());
                request.getRequestDispatcher("admin/SysCategoryAdmin.jsp").forward(request, response);
            }else{
                PageControl pc = new PageControl(curPageStr, sysCategoryDao.count());
                List<SysCategory>  categories= sysCategoryDao.getSysCategoryByPage(curPageStr,pc.getPageSize());
                pc.setList(categories);//获取当前页码系统分类
                request.setAttribute("scgList", pc.getList());
                request.setAttribute("curPage", pc.getCurPage());
                request.setAttribute("totalPages", pc.getTotalPages());
                request.getRequestDispatcher("admin/SysCategoryAdmin.jsp").forward(request, response);
            }
        }else if(method.equals("EditSysCategory")){//编辑系统分类
            int scgId = Integer.parseInt(request.getParameter("scgId"));
            SysCategory scg = sysCategoryDao.getById(scgId);
            request.setAttribute("scg", scg);
            request.getRequestDispatcher("admin/EditSysCategory.jsp").forward(request, response);
        }else if(method.equals("SaveEditSysCategory")){//保存系统分类编辑
            int scgId = Integer.parseInt(request.getParameter("scgId"));
            String scgName = request.getParameter("scgName");
            SysCategory scg = sysCategoryDao.getByName(scgName);
            if ((null != scg) && (scgId != scg.getId())) {
                request.getSession().setAttribute("scgExist", "该分类名已存在，请重新输入分类名！");
                response.sendRedirect("admin/EditSysCategory.jsp?scgId="+scgId);
            } else {//允许更新该分类名
                int res = sysCategoryDao.updateSysCategory(scgId, scgName);
                if (res > 0) {	//更新成功
                    request.getSession().setAttribute("succUpdateScg", "更新分类成功！");
                    response.sendRedirect("admin?method=SysCategoryAdmin");
                } else {
                    request.getSession().setAttribute("errorUpdateScg", "更新分类失败！");
                    response.sendRedirect("admin?method=SysCategoryAdmin");
                }
            }
        }else if(method.equals("AddSysCategory")){//添加系统分类
            String scgName = request.getParameter("scgName");
            SysCategory scg = sysCategoryDao.getByName(scgName);
            if (null != scg) {    //提示该分类已存在
                request.getSession().setAttribute("scgExist", "该分类名已存在，请重新输入分类名！");
                response.sendRedirect("admin/AddSysCategory.jsp");
            } else {
                int res = sysCategoryDao.insertSysCategory(scgName);
                if (res > 0) {	  //添加分类成功
                    request.getSession().setAttribute("succAddScg", "添加分类成功！");
                } else {		  //添加分类失败
                    request.getSession().setAttribute("errorAddScg", "添加分类失败！");
                }
                response.sendRedirect("admin?method=SysCategoryAdmin");
            }
        }else if(method.equals("DeleteSysCategory")){
            int scgId = Integer.parseInt(request.getParameter("scgId"));
            //SysCategoryDao scgDao = new SysCategoryDao();
            int res = sysCategoryDao.deleteSysCategory(scgId);
            if (res > 0) {
                request.getSession().setAttribute("succDeleScg", "删除分类成功！");
            } else {
                request.getSession().setAttribute("errorDeleScg", "删除分类失败！");
            }
            response.sendRedirect("admin?method=SysCategoryAdmin");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
